package com.jt.handler;

import com.jt.msg.req.LocationMsg;
import com.jt.msg.resp.CommonResp;
import com.jt.utils.ForwardLocationData;
import com.jt.utils.ForwardUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 位置包
 *
 * @author wang xiao
 * date 2023/8/9
 */

@Component
@ChannelHandler.Sharable
public class LocationMsgHandler extends BaseHandler<LocationMsg> {


    private ForwardUtil forwardUtil;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LocationMsg msg) throws Exception {
        log.info("source location msg:{}",msg.toString());
        CommonResp resp = CommonResp.success(msg, getSerialNumber(ctx.channel()));
        write(ctx, resp);
        forwardUtil.forwardData(toForwardLocationData(msg));
    }

    @Autowired
    public void setForwardUtil(ForwardUtil forwardUtil) {
        this.forwardUtil = forwardUtil;
    }

    private ForwardLocationData toForwardLocationData(LocationMsg locationMsg){
        ForwardLocationData data = new ForwardLocationData();
        data.setDevNum(locationMsg.getHeader().getTerminalId());
        data.setAlarm(locationMsg.getAlarm());
        data.setStatus(locationMsg.getStatusField());
        data.setLatitude(locationMsg.getLatitude());
        data.setLongitude(locationMsg.getLongitude());
        data.setElevation(locationMsg.getElevation());
        data.setSpeed(locationMsg.getSpeed());
        data.setDirection(locationMsg.getDirection());
        data.setTime(locationMsg.getTime());
        data.setMileage(locationMsg.getMileage());

        data.setAccEnable(getShitValueOfBool(data.getStatus(),0));
        data.setLocateEnable(getShitValueOfBool(data.getStatus(),1));
        data.setLatitudeType(getShitValue(data.getStatus(),2));
        data.setLongitudeType(getShitValue(data.getStatus(),3));

        data.setSpeedingWarn(getShitValueOfBool(data.getAlarm() ,1));
        data.setPowerVoltageWarn(getShitValueOfBool(data.getAlarm() ,7));
        data.setPowerFailure(getShitValueOfBool(data.getAlarm() ,8));
        return data;
    }

    private Integer getShitValue(Integer sourceValue,int shit){
        return (sourceValue >> shit) & 1;
    }

    private Boolean getShitValueOfBool(Integer sourceValue,int shit){
        return getShitValue(sourceValue,shit) ==1;
    }
}
